<template>
  <div class="cart-container">
    <!-- 左侧侧边栏 -->
    <div class="sidebar">
      <PersonalCenterSidebar />
    </div>

    <!-- 右侧内容区域 -->
    <div class="content-area">
      <el-table :data="tableData" border style="width: 100%; max-width: 1000px; margin: 0 auto;">
        <!-- 添加选择列 -->
        <el-table-column
            label="选择"
            width="50"
            align="center"
        >
          <template #default="scope">
            <el-checkbox v-model="scope.row.selected"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column
            label="商品图片"
            width="120"
            align="center"
        >
          <template #default="scope">
            <img :src="getImageUrl(scope.row.imageUrl)" alt="商品图片" style="max-width: 100%; max-height: 100px;">
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" min-width="150"/>
        <el-table-column prop="storeName" label="店铺" min-width="120"/>
        <el-table-column prop="price" label="商品价格" min-width="100"/>
        <el-table-column prop="quantity" label="商品数量" min-width="100"/>
        <el-table-column label="操作" min-width="100">
          <template #default="scope">
            <el-popconfirm title="确定移除吗?" @confirm="handleDelete(scope.row.id)">
              <template #reference>
                <el-button type="text">移除购物车</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 已选商品总价显示 -->
      <div class="total-price">已选商品 ¥<span id="totalPrice">0</span></div>

      <!-- 结算按钮 -->
      <div class="settlement-button-container">
        <el-button type="success" @click="generateOrder">购买</el-button>
        <el-button type="primary" @click="calculateTotal">结算</el-button>
        <el-button type="primary" @click="goBack">返回</el-button>
      </div>

      <!-- 全选 checkbox -->
      <div class="all-select">
        <el-checkbox v-model="allSelected" @change="handleAllSelect">全选</el-checkbox>
      </div>

      <!-- 底部分页 -->
      <div v-if="showPagination" style="margin: 10px 0">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";
import router from "@/router"; // 引入路由实例
import PersonalCenterSidebar from "@/views/PersonalCenterSidebar.vue";

export default {
  name: 'Cart',
  components: {PersonalCenterSidebar},
  data() {
    return {
      form: {},
      dialogVisible: false,
      search: '',
      currentPage: 1,
      total: 10,
      pageSize: 10,
      tableData: [],
      userId: '1',
      showPagination: false,
      allSelected: false
    }
  },
  created() {
    this.load().then(() => {
      // 初始化表格数据时为每个商品添加selected属性
      this.tableData.forEach(item => {
        item.selected = false;
      });
    });
  },
  methods: {
    handleDelete(id) {
      request.delete("/user/cancelCart/" + id).then(res => {
        if (res.code === '0') {
          this.$message({
            type: "success",
            message: '移除成功'
          })
        } else {
          this.$message({
            type: "error",
            message: "移除失败"
          })
        }
        this.load(); // 删除后需要重新加载表格
      })
    },
    searchItems() {
      // 这里可以添加搜索逻辑，例如根据输入框的值重新加载表格数据
      this.load();
    },
    handleSizeChange() {
      // 改变当前个数触发
      this.load(); // 重新刷新表格数据
    },
    handleCurrentChange() {
      // 改变当前页数触发
      this.load(); // 重新刷新表格数据
    },
    load() {
      return request.get("/user/cartSelectPage", {
        params: {
          userId: this.userId, // 用户id
          pageNumber: this.currentPage,
          pageSize: this.pageSize,
          search: this.search
        }
      }).then(res => {
        this.tableData = res.data.list;
        this.total = res.data.total;
        return res;
      })
    },
    calculateTotal() {
      let totalPrice = 0;
      this.tableData.forEach((item) => {
        if (item.selected) {
          totalPrice += item.price * item.quantity;
        }
      });
      document.getElementById('totalPrice').innerText = totalPrice;
      this.$message({
        type: 'success',
        message: `选中商品总价为：${totalPrice}`
      });
    },
    generateOrder() {
      // 获取选中的商品项
      const selectedItems = this.tableData.filter(item => item.selected);
      console.log(selectedItems);
      if (selectedItems.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要购买的商品'
        });
        return;
      }

      // 假设这里调用后端创建订单的接口，传入商品项信息
      request.post('/user/createOrder', {items: selectedItems})
          .then(res => {
            if (res.code === '0') {
              this.$message({
                type: 'success',
                message: '订单生成成功'
              });
              // 清空购物车选中状态
              this.tableData.forEach(item => {
                item.selected = false;
              });
            } else {
              this.$message({
                type: 'error',
                message: '订单生成失败'
              });
            }
          })
          .catch(err => {
            this.$message({
              type: 'error',
              message: '订单生成失败，请重试'
            });
          });
    },
    handleAllSelect() {
      this.tableData.forEach(item => {
        item.selected = this.allSelected;
      });
    },
    getImageUrl(imagePath) {
      return imagePath.startsWith('http') ? imagePath : require(`@/${imagePath}`);
    },
    goBack() {
      router.go(-1);
    }
  }
}
</script>

<style scoped>
/* 容器样式 */
.cart-container {
  display: flex;
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-width: 1200px;
  margin: 0 auto;
}

/* 左侧侧边栏样式 */
.sidebar {
  width: 250px;
  margin-right: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

/* 右侧内容区域样式 */
.content-area {
  flex-grow: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

/* 表格样式 */
.el-table {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
  margin-top: 20px;
}

.el-table th {
  background-color: #f0f0f0;
  color: #555;
  font-size: 16px;
  text-align: center;
}

.el-table td {
  vertical-align: middle;
  text-align: center;
}

.el-table tbody tr {
  transition: background-color 0.3s ease;
}

.el-table tbody tr:hover {
  background-color: #f5f5f5;
}

/* 总价显示区域样式 */
.total-price {
  font-size: 18px;
  color: #333;
  margin: 20px 0;
  text-align: center;
}

/* 结算按钮样式 */
.settlement-button-container {
  text-align: center;
  margin-bottom: 20px;
}

.el-button {
  margin: 0 5px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: scale(1.05);
}

/* 全选 checkbox 样式 */
.all-select {
  text-align: center;
  margin: 20px 0;
}

/* 分页按钮样式 */
.el-pagination {
  text-align: center;
  margin-top: 20px;
}

.el-pagination button {
  background-color: #f5f5f5;
  color: #333;
  border: none;
  padding: 5px 10px;
}

.el-pagination button:hover {
  background-color: #e9e9e9;
  color: #333;
}
</style>